
import React, { Component } from 'react'
import { UserOutlined } from '@ant-design/icons';
import router from '../../router'
import MyNavLink from '../MyNavLink'
import { Icon } from '@ant-design/compatible';
import storageUtils from '../../utils/storageUtils'
//ant
import { Menu} from 'antd';
import { NavLink, withRouter} from 'react-router-dom';
import logo from '../../assets/images/logo2.jpg'
import PubSub from 'pubsub-js'
import './index.scss';
const {SubMenu} = Menu;


class AsideMenu extends Component {

    hhh = (item)=>{
      console.log("点击事件",item)
      PubSub.publish("Tab", item)
    }
    //reduce+递归调用实现
    getMenuNodes = (menuList) =>{
        // 得到当前请求的path
      const path = this.props.location.pathname
      //console.log(path)
  
  
        return menuList.reduce((pre,item)=>{
          if(!item.children){
            pre.push((
              <Menu.Item key={item.key}>
              <MyNavLink to={item.key} title={item.title} onClick={()=>{this.hhh(item)}}>
               <Icon type={item.icon}/>
               
                <span>{item.title}</span>
                </MyNavLink>
              </Menu.Item>
            ))
          }else{
            // 如果当前请求路由与当前菜单的某个子菜单的key匹配, 将菜单的key保存为openKey
            const cItem = item.children.find(cItem => cItem.key===path)
            //console.log('cTtem'+cItem)
            if(cItem) {
              //console.log("为openKey进行赋值")
              
              this.openKey = item.key
              storageUtils.saveOpenKey(this.openKey) //保存到local中
             }
            pre.push((
                <SubMenu key={item.key}   
                title={
                  <span>
                    <Icon type={item.icon}/>
                    <span>{item.title}</span>
                  </span>
                }
                >
                {this.getMenuNodes(item.children)}
                </SubMenu>))
                
                 
  
          }
          return pre
        },[])
      }
      //在第一次render()之前执行一次,为第一个render()准备数据同步
     shouldComponentUpdate(){
  
       this.getMenuNodes(router);
       //console.log("执行shouldComponentUpdate")
      return true
     }
      render() {
        // 得到当前请求路径, 作为选中菜单项的key
        const selectKey = this.props.location.pathname
        //得到需要打开菜单项的key
        const openKey = storageUtils.getOpenKey() || this.openKey
       // console.log("openKey:"+openKey);
          return (
            <div className="left-nav"> 
            <div className="logo" ><img src={logo} style={{width:"30px"}} alt="logo" />后台管理系统</div>
            <Menu theme="dark" selectedKeys={[selectKey]}  defaultOpenKeys={[openKey]} mode="inline">
              {this.getMenuNodes(router)}
            </Menu>
            
            </div>
          )
      }
  }
  //使普通组件具有路由组件的属性
export default withRouter(AsideMenu);